<template>
  <div class="main-box">
    <!-- 搜索 -->
    <van-search
      v-model="searchValue"
      @search="getSearchValue"
      placeholder="请输入搜索关键词"
    />
    <!-- 列表 -->
    <div class="main-list" ref="listRef">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-for="(item, idx) in tableList" :key="idx">
          <div class="list-item">
            <img :src="item.img" alt="" />
            <div class="list-item-info">
              <p class="list-item-info-title">{{ item.title }}</p>
              <p class="item-item-info-price">金额：{{ item.price }}￥</p>
              <van-button size="mini" type="primary" @click="addShopCar(item)"
                >加入购物车</van-button
              >
            </div>
          </div>
        </van-cell>
      </van-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, Ref, reactive } from "vue";
import { apiGetList } from "@/api";
import { tablistItemType } from "@/interface";
import { useStore } from "vuex";

const store = useStore();

// ====================== 搜索 =========================
const searchValue = ref("");

// 搜索
const getSearchValue = () => {
  listRef.value.scrollTop = 0;
  pageInfo.current = 1;
  getList();
};

// ===================== 列表 ======================
const tableList: Ref<tablistItemType[]> = ref([]);

const listRef = ref();

// 是否属于加载状态
const loading = ref(false);

// 是否已经加载全部数据
const finished = ref(false);

// 上拉加载分页数据
const pageInfo = reactive({
  size: 10,
  current: 1,
  total: 0,
});

onMounted(() => {
  getList();
});

// 获取列表中的内容
const getList = () => {
  // 在加载前  需要打开loading
  loading.value = true;
  apiGetList({ ...pageInfo, search: searchValue.value }).then((res: any) => {
    // 赋值列表数据
    tableList.value = [...res.data];

    // 加载完成之后 关闭loading
    loading.value = false;

    // 判断是否还有数据可以获取
    if (res.data.length === res.total) {
      // 如果没有数据可以获取 将finished设置为true，onload就不在回触发
      finished.value = true;
    }
  });
};

// 当滚动条即将到到底底部时触发
const onLoad = () => {
  pageInfo.current += 1;

  getList();
};

// ============================ 添加购物车 ==========================
const addShopCar = (item: tablistItemType) => {
  store.commit('CHANGE_SHOP_CAR_LIST', item)
};
</script>

<style lang="scss" scoped>
.main-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.main-list {
  flex: 1;
  overflow-y: auto;
}

.list-item {
  width: 100%;
  display: flex;
}

.item-item-info-price {
  padding-bottom: 22px;
}

.list-item-info {
  // flex: 1;
  padding-left: 10px;
  // display: flex;
  flex-direction: column;
  text-align: left;
  justify-content: space-between;
}

.list-item-info-title {
  font-size: 20px;
  font-weight: 800;
  color: #333;
}
</style>
